//
//  MessageCell.m
//  Coding_My
//
//  Created by showXxie on 2017/8/22.
//  Copyright © 2017年 sooxie. All rights reserved.
//

#define kMessageCell_FontContent [UIFont systemFontOfSize:15]
#define kMessageCell_PadingWidth 20.0
#define kMessageCell_PadingHeight 11.0
#define kMessageCell_ContentWidth (kScreen_Width*0.6)
#define kMessageCell_TimeHeight 40.0
#define kMessageCell_UserIconWith 40.0

#import "MessageCell.h"
#import "UITapImageView.h"
#import "UICustomCollectionView.h"
#import "UILongPressMenuImageView.h"
#import "HtmlMedia.h"
#import "MessageMediaItemCCell.h"

@interface MessageCell ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic) PrivateMessage *curPriMsg, *prePriMsg;

@property (strong, nonatomic) UITapImageView *userIconView;
@property (strong, nonatomic) UICustomCollectionView *mediaView;
//@property (strong, nonatomic) BubblePlayView *voiceView;
@property (strong, nonatomic) NSMutableDictionary *imageViewsDict;

@property (strong, nonatomic) UIActivityIndicatorView *sendingStatus;
@property (strong, nonatomic) UITapImageView *failStatus;
@property (strong, nonatomic) UILabel *timeLabel;

@property (nonatomic, assign) CGFloat preMediaViewHeight;
@property (strong, nonatomic) UILongPressMenuImageView *bgImgView;
@property (strong, nonatomic) UIView *voiceView;

@end
@implementation MessageCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    if (self) {
        [self setUIWithReuseIdentifier:reuseIdentifier];
    }

    return self;
}

- (void)setUIWithReuseIdentifier:(NSString *)reuseIdentifier {
    
    //头像
    if (!_userIconView) {
        _userIconView = [[UITapImageView alloc] initWithFrame:CGRectMake(0, 0, kMessageCell_UserIconWith, kMessageCell_UserIconWith)];
        [_userIconView doCircleFrame];
        [self.contentView addSubview:_userIconView];
    }
    
    //背景
    if (!_bgImgView) {
        _bgImgView = [[UILongPressMenuImageView alloc] initWithFrame:CGRectZero];
        _bgImgView.userInteractionEnabled = YES;
        
        [self.contentView addSubview:_bgImgView];
    }

    //内容
    if (!_contentLabel) {
        _contentLabel = [[UITTTAttributedLabel alloc] initWithFrame:CGRectMake(kMessageCell_PadingWidth, kMessageCell_PadingHeight, 0, 0)];
        _contentLabel.numberOfLines = 0;
        _contentLabel.font =kMessageCell_FontContent;
        _contentLabel.textColor = [UIColor blackColor];
        _contentLabel.backgroundColor = [UIColor clearColor];
        //设置链接颜色
        _contentLabel.linkAttributes = kLinkAttributes;
        _contentLabel.activeLinkAttributes = kLinkAttributesActive;
        [_bgImgView addSubview:_contentLabel];
    }

    
    if ([reuseIdentifier isEqualToString:kCellIdentifier_MessageMedia]) {

        if (!self.mediaView) {
            UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
            self.mediaView = [[UICustomCollectionView alloc] initWithFrame:CGRectMake(kMessageCell_PadingWidth, kMessageCell_PadingHeight, kMessageCell_ContentWidth, 80) collectionViewLayout:layout];
            self.mediaView.scrollEnabled = NO;
            [self.mediaView setBackgroundView:nil];
            [self.mediaView setBackgroundColor:[UIColor clearColor]];
            [self.mediaView registerClass:[MessageMediaItemCCell class] forCellWithReuseIdentifier:kCCellIdentifier_MessageMediaItem];
            [self.mediaView registerClass:[MessageMediaItemCCell class] forCellWithReuseIdentifier:kCCellIdentifier_MessageMediaItem_Single];
            self.mediaView.dataSource = self;
            self.mediaView.delegate = self;
            [_bgImgView addSubview:self.mediaView];
        }
        if (!_imageViewsDict) {
            _imageViewsDict = [[NSMutableDictionary alloc] init];
        }
        
    } else if ([reuseIdentifier isEqualToString:kCellIdentifier_MessageVoice]) {
       
        if (!_voiceView) {
            _voiceView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kMessageCell_ContentWidth, 40)];
            _voiceView.backgroundColor = [UIColor purpleColor];
            [_bgImgView addSubview:_voiceView];
        }
    }
    
    
    
    
}


#pragma mark - 设置数据
- (void)setCurPriMsg:(PrivateMessage *)curPriMsg andPrePriMsg:(PrivateMessage *)prePriMsg {
  
    CGFloat mediaViewHeight = [MessageCell mediaViewHeightWithObj:curPriMsg];

    
    BOOL isMyMsg = [curPriMsg.sender.global_key isEqualToString:@"sooxie"];
    
    if (_curPriMsg == curPriMsg && _prePriMsg == prePriMsg) {
        
        if (_voiceView) {

        }
        
        
        return;
    }else{
        _curPriMsg = curPriMsg;
        _prePriMsg = prePriMsg;
    }
    //无当条数据
    if (!_curPriMsg) {
        return;
    }
    
    CGFloat curBottomY = 0;
    
    //是否有时间显示
    NSString *displayStr = [MessageCell displayTimeStrWithCurMsg:_curPriMsg preMsg:_prePriMsg];
    //显示时间label 固定高度
//    displayStr = @"刚刚";
    if (displayStr) {
        if (!_timeLabel) {
            _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(kPaddingLeftWidth, (kMessageCell_TimeHeight- 20)/2, kScreen_Width-2*kPaddingLeftWidth, 20)];
            _timeLabel.backgroundColor = [UIColor clearColor];
            _timeLabel.font = [UIFont systemFontOfSize:12];
            _timeLabel.textColor = kColor999;
            _timeLabel.textAlignment = NSTextAlignmentCenter;
            [self.contentView addSubview:_timeLabel];
        }
        _timeLabel.hidden = NO;
        _timeLabel.text = displayStr;
        curBottomY += kMessageCell_TimeHeight;
    }else{
        _timeLabel.hidden = YES;
    }
    
    UIImage *bgImg;
    CGSize bgImgViewSize;
    CGSize textSize;
    
    
    
    //存在文字内容  宽度为屏幕宽0.6倍 获取文字内容高度
    if (_curPriMsg.content.length > 0) {
        textSize = [_curPriMsg.content getSizeWithFont:kMessageCell_FontContent constrainedToSize:CGSizeMake(kMessageCell_ContentWidth, CGFLOAT_MAX)];
    }else{
        textSize = CGSizeZero;
    }
    
    
    [_contentLabel setWidth:kMessageCell_ContentWidth];
    _contentLabel.text = _curPriMsg.content;
    [_contentLabel sizeToFit];
    
    
    for (HtmlMediaItem *item in _curPriMsg.htmlMedia.mediaItems) {
        
        //存在链接  或者 @谁时
        if (item.displayStr.length > 0 && item.href.length > 0) {
            
            //设置超链接 起始位置和长度
            [self.contentLabel addLinkToTransitInformation:[NSDictionary dictionaryWithObject:item forKey:@"value"] withRange:item.range];
        }
    }
    
    textSize.height = CGRectGetHeight(_contentLabel.frame);
    //设置文字y
//    [_contentLabel setY:kMessageCell_PadingHeight];
    
    if (mediaViewHeight > 0) {
        
        
        [_contentLabel setY:2*kMessageCell_PadingHeight + mediaViewHeight];
        //宽度猴子表情 或者屏幕0.6
        CGFloat contentWidth = [_curPriMsg isSingleBigMonkey]? [MessageMediaItemCCell monkeyCcellSize].width : kMessageCell_ContentWidth;
        
        //设置背景size 根据是否图文混排
        bgImgViewSize = CGSizeMake(contentWidth +2*kMessageCell_PadingWidth,
                                   mediaViewHeight +textSize.height + kMessageCell_PadingHeight*(_curPriMsg.content.length > 0? 3:2));

        
    }else {
        [_contentLabel setY:kMessageCell_PadingHeight];
        //  设置背景尺寸 文字距离背景的padding 为20
        bgImgViewSize = CGSizeMake(textSize.width +2*kMessageCell_PadingWidth, textSize.height +2*kMessageCell_PadingHeight);
    }
    
    
    
    if (_voiceView) {

        bgImgViewSize = CGSizeMake(_voiceView.frame.size.width, 40);

    }




    CGRect bgImgViewFrame;

    if (!isMyMsg) {
        // 这是好友发的   在左边显示 x = 左边距 + 头像宽度
//        y = 上边距 + 时间高度
        bgImgViewFrame = CGRectMake(kPaddingLeftWidth +kMessageCell_UserIconWith, curBottomY +kMessageCell_PadingHeight, bgImgViewSize.width, bgImgViewSize.height);
       
        [_userIconView setCenter:CGPointMake(kPaddingLeftWidth +kMessageCell_UserIconWith/2, CGRectGetMaxY(bgImgViewFrame)- kMessageCell_UserIconWith/2)];
        _bgImgView.frame = bgImgViewFrame;

    }else {
        //        这是自己发的
        bgImgViewFrame = CGRectMake((kScreen_Width - kPaddingLeftWidth - kMessageCell_UserIconWith) -bgImgViewSize.width, curBottomY +kMessageCell_PadingHeight, bgImgViewSize.width, bgImgViewSize.height);
        [_userIconView setCenter:CGPointMake(kScreen_Width - kPaddingLeftWidth -kMessageCell_UserIconWith/2, CGRectGetMaxY(bgImgViewFrame)- kMessageCell_UserIconWith/2)];
        _bgImgView.frame = bgImgViewFrame;

    }
    
    //设置背景图片
    bgImg = [UIImage imageNamed:isMyMsg? @"messageRight_bg_img": @"messageLeft_bg_img"];
    //拉伸边部
    bgImg = [bgImg resizableImageWithCapInsets:UIEdgeInsetsMake(18, 30, bgImg.size.height - 19, bgImg.size.width - 31)];
    
    //设置头像图片
    [_userIconView sd_setImageWithURL:[NSURL URLWithString:curPriMsg.sender.avatar] placeholderImage:kPlaceholderMonkeyRoundView(_userIconView)];
    
    [_bgImgView setImage:bgImg];

    //_meidaView设置frame 和更新数据
    if (_mediaView) {
        CGFloat contentWidth = [_curPriMsg isSingleBigMonkey]? [MessageMediaItemCCell monkeyCcellSize].width : kMessageCell_ContentWidth;
        [_mediaView setSize:CGSizeMake(contentWidth, mediaViewHeight)];
        [_mediaView reloadData];
    }

}


#pragma mark - 设置cell 的高度
+ (CGFloat)cellHeightWithObj:(id)obj preObj:(id)preObj{

    CGFloat cellHeight = 0;
    if ([obj isKindOfClass:[PrivateMessage class]]) {
        
        PrivateMessage *curPriMsg = (PrivateMessage *)obj;
        CGSize textSize = [curPriMsg.content getSizeWithFont:kMessageCell_FontContent constrainedToSize:CGSizeMake(kMessageCell_ContentWidth, CGFLOAT_MAX)];
      
        CGFloat mediaViewHeight = [MessageCell mediaViewHeightWithObj:curPriMsg];

        cellHeight += mediaViewHeight;

        
        
        if ([curPriMsg isVoice]) {
            cellHeight += kMessageCell_PadingHeight*2+40;
        } else {
            cellHeight += textSize.height + kMessageCell_PadingHeight*4;
        }
        
        if (mediaViewHeight > 0 && curPriMsg.content && curPriMsg.content.length > 0) {
            cellHeight += kMessageCell_PadingHeight;
        }
       
        PrivateMessage *prePriMsg = (PrivateMessage *)preObj;
       
        NSString *displayStr = [MessageCell displayTimeStrWithCurMsg:curPriMsg preMsg:prePriMsg];

        if (displayStr) {
            cellHeight += kMessageCell_TimeHeight;
        }
        

    }
    

    
    return cellHeight;
}

#pragma mark - 时间显示
+ (NSString *)displayTimeStrWithCurMsg:(PrivateMessage *)cur preMsg:(PrivateMessage *)pre{
    NSString *displayStr = nil;
    NSDate *curDate = [NSDate dateFromTimeString:cur.created_at];
    NSDate *preDate = [NSDate dateFromTimeString:pre.created_at];

    //没有上一条数据 或者和上一条数据的时间间隔大于60秒
    if (!pre || [curDate timeIntervalSinceDate:preDate] > 1*60) {
        displayStr = [curDate stringDisplay_HHmm];
    }
    return displayStr;
}

#pragma mark - 图片高度
+ (CGFloat)mediaViewHeightWithObj:(PrivateMessage *)curPriMsg{
    CGFloat mediaViewHeight = 0;
    
    if (curPriMsg.hasMedia) {
        
        if (curPriMsg.nextImg) {
            

        }else {
            //猴子表情
            if ([curPriMsg isSingleBigMonkey]) {
              
                mediaViewHeight += [MessageMediaItemCCell monkeyCcellSize].height;

            }else {//图片
                
                for (HtmlMediaItem *curItem in curPriMsg.htmlMedia.imageItems) {
                    mediaViewHeight += [MessageMediaItemCCell ccellSizeWithObj:curItem].height +kMessageCell_PadingHeight;
                }

                mediaViewHeight -= kMessageCell_PadingHeight;

            }
            
            
        }

    }

    
    return mediaViewHeight;
}



#pragma mark collectionView 图片

#pragma mark Collection M
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (!_curPriMsg) {
        return 0;
    }
    NSUInteger mediaCount = (_curPriMsg.htmlMedia && _curPriMsg.htmlMedia.imageItems.count> 0)? _curPriMsg.htmlMedia.imageItems.count : 1;
    return mediaCount;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
   
    MessageMediaItemCCell *ccell = [collectionView dequeueReusableCellWithReuseIdentifier:[_curPriMsg isSingleBigMonkey]? kCCellIdentifier_MessageMediaItem_Single: kCCellIdentifier_MessageMediaItem forIndexPath:indexPath];
    
    ccell.refreshMessageMediaCCellBlock = self.refreshMessageMediaCCellBlock;

    if (_curPriMsg.nextImg) {
//        ccell.curObj = _curPriMsg.nextImg;
    }else{
        HtmlMediaItem *curItem = [_curPriMsg.htmlMedia.imageItems objectAtIndex:indexPath.row];
        ccell.curObj = curItem;
    }
    [_imageViewsDict setObject:ccell.imgView forKey:indexPath];
    return ccell;

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize itemSize = CGSizeZero;
    if (_curPriMsg.nextImg) {
        itemSize = [MessageMediaItemCCell ccellSizeWithObj:_curPriMsg.nextImg];
    }else{
        if ([_curPriMsg isSingleBigMonkey]) {
            itemSize = [MessageMediaItemCCell monkeyCcellSize];
        }else{
            HtmlMediaItem *curItem = [_curPriMsg.htmlMedia.imageItems objectAtIndex:indexPath.row];
            itemSize = [MessageMediaItemCCell ccellSizeWithObj:curItem];
        }
    }
    return itemSize;
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsZero;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return kMessageCell_PadingHeight;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}




@end
